package com.itdfq.loginuser.service;

import com.itdfq.common.pojo.Result;
import com.itdfq.common.redislock.annotation.DisLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author: GodChin
 * @Date: 2021/8/23 9:21
 * @Blog: itdfq.com
 * @QQ: 909256107
 * @Description:
 */
@Service
public class RedisService {
    @Autowired
    private RedisTemplate redisTemplate;


    private static final String KEY = "study:lock:sum";
    private static final Long EXPIRE_SECOND = 10000L;

    public void putToken(String token, Integer userId) {
        redisTemplate.opsForValue().setIfAbsent(token, userId, 1, TimeUnit.DAYS);
    }

    public Integer getToken(String key) {
        return (Integer) redisTemplate.opsForValue().get(key);

    }


    @DisLock(key = "'user:' + #skuId", expire = 100000L)
    public Result lockTest(Integer skuId) {
        Integer sum = (Integer) redisTemplate.opsForValue().get(KEY);
        if (sum > 0) {
            try {
                Thread.sleep(80000);
            } catch (InterruptedException e) {
                Thread.currentThread();
            }
            redisTemplate.opsForValue().set(KEY, sum - 1, EXPIRE_SECOND, TimeUnit.SECONDS);
            return Result.success("购买成功，剩余库存" + (sum - 1));
        }
        return Result.fail("没有库存");
    }
}
